package com.sunshine.Service.impl;


import cn.hutool.core.util.RandomUtil;

import com.sunshine.Service.UserService;
import com.sunshine.domain.user;
import com.sunshine.domain.userExample;
import com.sunshine.domain.userPhone;
import com.sunshine.mapper.userMapper;
import com.sunshine.util.JwtUtil;
import com.sunshine.util.minio.MinIOService;

import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private MinIOService minIOService;

    @Autowired
    private userMapper usermapper;

/*    @Autowired
    private RedisTemplate<String, Object> redisTemplate;*/

    @Autowired
    private RedissonClient redissonClient;

    // 在适当的位置创建自定义异常类
    public class LoginException extends RuntimeException {
        public LoginException(String message) {
            super(message);
        }
    }

    @Override
    public user register(String username, String password) {
        // 检查用户名是否已存在
        userExample example = new userExample();
        example.createCriteria().andUsernameEqualTo(username);
        user user = new user();
        Date date = new Date();
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        user.setUsername(username);
        user.setCreatetime(date);
        user.setPassword(bCryptPasswordEncoder.encode(password));
        usermapper.insert(user);
        
        // 插入后，user对象将包含数据库生成的ID
        return user;
    }

    /**
     * 用户登录验证方法
     * <p>该方法通过用户名和密码验证用户身份，如果验证成功则生成JWT token并存储到Redis中</p>
     *
     * @param username 用户名
     * @param password 密码
     * @return 登录成功的用户对象，如果登录失败则返回null
     */
    @Override
    public user login(String username, String password) {
        userExample example = new userExample();
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        example.createCriteria().andUsernameEqualTo(username);
        List<user> users = usermapper.selectByExample(example);
        if (!users.isEmpty()){
            //验证密码是否匹配
            boolean matches = encoder.matches(password, users.get(0).getPassword());
            if (matches){
                user user = users.get(0);
                user.setStatus( true);
                String token = JwtUtil.createToken(users.get(0).getId(), users.get(0).getUsername());
                user.setToken(token);
                //把token保存到redis数据库
                redissonClient.getBucket("user_token:" + user.getId()).set(token, 24, TimeUnit.HOURS);
                usermapper.updateByPrimaryKey(user);
                return users.get(0);
            }

        }
        throw new LoginException("用户名或密码错误");
    }

    @Override
    public userPhone loginByPhone(userPhone  phone ) {
        String phone1 = phone.getPhone();
        userExample example = new userExample();
        example.createCriteria().andPhoneEqualTo(phone1);
        List<user> users = usermapper.selectByExample(example);
        //如果手机号没注册过
        if (users.isEmpty()){
            user user = new user();
            user.setPhone(phone1);
            Date date = new Date();
            user.setUpdatetime(date);
            user.setCreatetime(date);
            usermapper.insert(user);
        }
        //生成验证码
        String s = RandomUtil.randomNumbers(4);

        //保存短信验证码，手机号，有效期，是否使用


        //对接短信通道，发送短信

        return phone;

    }

    @Override
    public String logout(Integer  id) {
        usermapper.deleteByPrimaryKey( id);
        return "注销成功";
    }

    @Override
    public user updateUserInfo(Integer id, String username, String phone, MultipartFile head) {
        user user = new user();
        user.setId(id);
        user.setUsername(username);
        user.setPhone(phone);
        // 只有在提供了商品图片时才执行上传逻辑
        if (head!= null && !head.isEmpty()) {
            try {
                // 确保存储桶存在
                minIOService.createBucketIfNotExists();
                String s = minIOService.uploadFile(head);
                user.setHead(s);
            } catch (Exception e) {
                throw new RuntimeException("添加图片失败: " + e.getMessage());
            }
        }
        usermapper.updateByPrimaryKeySelective(user);
        return user;
    }

    @Override
    public String updatePassword(Integer id, String oldpassword, String newpassword) {
        // 查询用户信息
        user user1 = usermapper.selectByPrimaryKey(id);
        if (user1 == null) {
            return "用户不存在";
        }

        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

        // 检查密码是否为空
        if (oldpassword == null || oldpassword.isEmpty() || newpassword == null || newpassword.isEmpty()) {
            return "密码不能为空";
        }

        // 验证用户输入的旧密码是否正确
        boolean matches = encoder.matches(oldpassword, user1.getPassword());
        if (!matches) {
            return "原密码错误";
        }

        // 检查新密码是否与旧密码相同
        if (encoder.matches(newpassword, user1.getPassword())) {
            return "新密码不能与原密码相同";
        }

        // 创建更新对象
        user user = new user();
        user.setId(id);
        // 对新密码进行加密
        user.setPassword(encoder.encode(newpassword));

        // 更新密码
        int result = usermapper.updateByPrimaryKeySelective(user);
        if (result <= 0) {
            return "密码更新失败";
        }
        
        //删除redis里面的token
        redissonClient.getBucket("user_token:" + id).delete();
        return "修改成功，请重新登录";
    }



}